"""
Created on 26-Jan-2010

@author: dexen
"""
import sys
import time
import threading as th
import Queue as qu

from dexen.system.base.task import InputUnit, OutputUnit

#from dexen.system.base.exceptions import ScriptException, SlaveException


class SlaveComm(object):
    def __init__(self, slavename, slavedir):
        self.inq = qu.Queue()
        self.outq = qu.Queue()
        self.slavename = slavename
        self.slavedir = slavedir
        #sys.path.append(slavedir)
        self.lock = th.RLock()
    
    def reset(self):
        with self.lock:
            self.inq = qu.Queue()
            self.out = qu.Queue()
    
    def set_env(self, masterdir):
        self.masterdir = masterdir
        sys.path.append(masterdir)
    
    def get_env(self):
        return self.masterdir
    
    def reset_env(self):
        sys.path = sys.path[:-1]
    
    def put_input(self, unit):
        assert isinstance(unit, InputUnit)
        with self.lock:
            self.inq.put(unit)
    
    def has_input(self):
        with self.lock:
            return not self.inq.empty()
        
    def get_input(self):
        with self.lock:
            if not self.inq.empty():
                input = self.inq.get()
                return input
            return None
    
    def put_output(self, unit):
        assert isinstance(unit, OutputUnit)
        with self.lock:
            self.outq.put(unit)
    
    def get_output(self):
        ret = None
        try:
            ret = self.outq.get_nowait()
        except qu.Empty:
            #print "queue empty exception is caught breaking out of the loop"
            pass
        return ret
    def get_slavename(self):
        return self.slavename
    
    def get_slavedir(self):
        return self.slavedir
    

def test():
    pass
    from dexen.system.base import MyManager
    
    MyManager.register("SlaveComm", SlaveComm)
    mgr = MyManager()
    mgr.start()
    
    c = mgr.SlaveComm("SLAVE_TT", "")
    print c.get_exc()
    print c.can_put()


if __name__ == "__main__":
    test()
